package com.shop.cereshop.app.service.buyer.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.dao.buyer.CereBuyerUserDAO;
import com.shop.cereshop.app.dao.distributor.CereShopDistributorDAO;
import com.shop.cereshop.app.page.buyer.MyUser;
import com.shop.cereshop.app.page.login.BuyerUser;
import com.shop.cereshop.app.page.seckill.SeckillProductAnswer;
import com.shop.cereshop.app.page.seckill.SeckillProductProblem;
import com.shop.cereshop.app.param.buyer.UserParam;
import com.shop.cereshop.app.param.index.LoginParam;
import com.shop.cereshop.app.param.index.LoginPhoneParam;
import com.shop.cereshop.app.param.index.UpdateWxPhoneParam;
import com.shop.cereshop.app.service.activity.CereBuyerCouponService;
import com.shop.cereshop.app.service.buyer.*;
import com.shop.cereshop.app.service.cart.CereShopCartService;
import com.shop.cereshop.app.service.collect.CereBuyerCollectService;
import com.shop.cereshop.app.service.collect.CereBuyerFootprintService;
import com.shop.cereshop.app.service.distributor.CereDistributorBuyerService;
import com.shop.cereshop.app.service.groupwork.CereCollageOrderService;
import com.shop.cereshop.app.service.notice.CereNoticeService;
import com.shop.cereshop.app.service.order.CereShopOrderService;
import com.shop.cereshop.app.service.seckill.CereProductAnswerService;
import com.shop.cereshop.app.service.seckill.CereProductProblemService;
import com.shop.cereshop.app.service.shop.CereShopCommentService;
import com.shop.cereshop.app.service.shop.CereShopVisitService;
import com.shop.cereshop.app.utils.WechatUtil;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.constant.StringEnum;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.canvas.CerePlatformCanvas;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.common.PageParam;
import com.shop.cereshop.commons.domain.distributor.CereShopDistributor;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.EncryptUtil;
import com.shop.cereshop.commons.utils.RandomStringUtil;
import com.shop.cereshop.commons.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CereBuyerUserServiceImpl implements CereBuyerUserService {
    @Value("${Dl_Message.shopId}")
    private Long shopId;
    @Value("${Dl_Message.grade}")
    private Long grade;

    @Autowired
    private CereBuyerUserDAO cereBuyerUserDAO;

    @Autowired
    private CereProductProblemService cereProductProblemService;

    @Autowired
    private CereProductAnswerService cereProductAnswerService;

    @Autowired
    private CereBuyerBankService cereBuyerBankService;

    @Autowired
    private CereBuyerCollectService cereBuyerCollectService;

    @Autowired
    private CereBuyerCommentLikeService cereBuyerCommentLikeService;

    @Autowired
    private CereBuyerCouponService cereBuyerCouponService;

    @Autowired
    private CereBuyerShopCouponService cereBuyerShopCouponService;

    @Autowired
    private CereBuyerFootprintService cereBuyerFootprintService;

    @Autowired
    private CereBuyerLabelService cereBuyerLabelService;

    @Autowired
    private CereBuyerReceiveService cereBuyerReceiveService;

    @Autowired
    private CereBuyerSearchService cereBuyerSearchService;

    @Autowired
    private CereBuyerShopLabelService cereBuyerShopLabelService;

    @Autowired
    private CereBuyerWithdrawalService cereBuyerWithdrawalService;

    @Autowired
    private CereShopDistributorDAO cereShopDistributorDAO;

    @Autowired
    private CereCollageOrderService cereCollageOrderService;

    @Autowired
    private CereDistributorBuyerService cereDistributorBuyerService;

    @Autowired
    private CereNoticeService cereNoticeService;

    @Autowired
    private CereShopCommentService cereShopCommentService;

    @Autowired
    private CereShopVisitService cereShopVisitService;

    @Autowired
    private CereShopCartService cereShopCartService;

    @Autowired
    private CereShopOrderService cereShopOrderService;

    @Override
    public CereBuyerUser findByToken(String token) {
        return cereBuyerUserDAO.findByToken(token);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public BuyerUser wxLogin(LoginParam param) throws CoBusinessException {
        BuyerUser user = null;
        String time = TimeUtils.yyMMddHHmmss();
        //根据微信code获取unionId
        JSONObject wx = WechatUtil.getOpenId(param.getCode());
        String openid = wx.get("openid").toString();
        String unionId = "";
        if (!EmptyUtils.isEmpty(wx.get("unionid"))) {
            unionId = wx.get("unionid").toString();
        }
        //查询该微信号是否已注册
        if (!EmptyUtils.isEmpty(openid)) {
            user = cereBuyerUserDAO.findByOpenid(openid);
            if (user == null) {
                //未注册
                user = new BuyerUser();
                user.setIfFirst(IntegerEnum.YES.getCode());
            } else {
                if (!EmptyUtils.isEmpty(param.getHeadImage())) {
                    //更新微信头像
                    CereBuyerUser cereBuyerUser = new CereBuyerUser();
                    cereBuyerUser.setBuyerUserId(user.getBuyerUserId());
                    cereBuyerUser.setHeadImage(param.getHeadImage());
                    cereBuyerUserDAO.updateByPrimaryKeySelective(cereBuyerUser);
                }
                user.setIfFirst(IntegerEnum.NO.getCode());
            }
            user.setWechatOpenId(openid);
            return user;
        } else {
            throw new CoBusinessException(CoReturnFormat.WECHAT_ERROR);
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public BuyerUser wxAppLogin(LoginPhoneParam param) throws CoBusinessException {
        BuyerUser user = null;
        String time = TimeUtils.yyMMddHHmmss();
        //查询该微信号是否已注册
        if (!EmptyUtils.isEmpty(param.getWechatOpenId())) {
            user = cereBuyerUserDAO.findByOpenid(param.getWechatOpenId());
            if (user == null) {
                //未注册
                user = new BuyerUser();
                user.setIfFirst(IntegerEnum.YES.getCode());
            } else {
                user.setIfFirst(IntegerEnum.NO.getCode());
            }
            return user;
        } else {
            throw new CoBusinessException(CoReturnFormat.WECHAT_ERROR);
        }
    }

    @Override
    public CereBuyerUser selectById(Long buyerForwardUserId) {
        return cereBuyerUserDAO.selectByPrimaryKey(buyerForwardUserId);
    }

    @Override
    public CereBuyerUser getUserByid(String phone) {
        return cereBuyerUserDAO.selectByPrimaryKey(Long.valueOf(phone));
    }

    @Override
    public void upDateWxOpenId(Long buyerUserId, String wechatOpenId) {
        cereBuyerUserDAO.upDateWxOpenId(buyerUserId, wechatOpenId);
    }

    @Override
    public List<BuyerUser> getByWxOpenId(String wechatOpenId) {
        return cereBuyerUserDAO.getByWxOpenId(wechatOpenId);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public BuyerUser setWxPhone(LoginPhoneParam param) throws CoBusinessException {
        Map<String, Object> map = WechatUtil.getPhoneNumber(param);
        if (EmptyUtils.isEmpty(map)) {
            throw new CoBusinessException(CoReturnFormat.WECHAT_ERROR);
        }
        String phone = "";
        Object phoneNumber = map.get("param");
        String jsonString = JSONObject.toJSONString(phoneNumber);
        JSONObject obj = JSONObject.parseObject(jsonString);
        if (!EmptyUtils.isEmpty(jsonString)) {
            phone = obj.get("phoneNumber").toString();
        }
        BuyerUser result = new BuyerUser();
        result.setPhone(phone);
        String time = TimeUtils.yyMMddHHmmss();
        //校验手机号是否绑定其他微信
        CereBuyerUser cereBuyerUser = cereBuyerUserDAO.checkPhoneWx(phone);
        if (cereBuyerUser != null) {
            //绑定了微信
            if (!cereBuyerUser.getWechatOpenId().equals(param.getWechatOpenId())) {
                //如果和当前微信openid不一致，提示
                throw new CoBusinessException(CoReturnFormat.PHONE_ALREADY_WX);
            } else {
                //如果一致,直接返回用户信息
                result.setHeadImage(cereBuyerUser.getHeadImage());
                result.setToken(cereBuyerUser.getToken());
                result.setWechatOpenId(param.getWechatOpenId());
                result.setWechatName(cereBuyerUser.getWechatName());
                return result;
            }
        }
        //查询手机号已注册用户数据
        BuyerUser byPhone = cereBuyerUserDAO.findByPhone(phone);
        //查询微信已注册用户数据
        CereBuyerUser user = cereBuyerUserDAO.getByOpenid(param.getWechatOpenId());
        if (byPhone != null) {
            if (user != null) {
                //删除手机号注册用户
                cereBuyerUserDAO.deleteByPrimaryKey(byPhone.getBuyerUserId());
                //更新微信注册用户绑定手机号
                user.setPhone(byPhone.getPhone());
                user.setUpdateTime(time);
                user.setHeadImage(param.getHeadImage());
                cereBuyerUserDAO.updateByPrimaryKeySelective(user);
                result.setBuyerUserId(user.getBuyerUserId());
                result.setWechatOpenId(param.getWechatOpenId());
                result.setToken(user.getToken());
                result.setPhone(phone);
                //同步更新手机号注册的业务数据转移到微信注册用户
                //银行卡数据转移
                cereBuyerBankService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //收藏数据转移
                cereBuyerCollectService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //是否点赞数据转移
                cereBuyerCommentLikeService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //领取优惠券数据转移
                cereBuyerCouponService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                cereBuyerShopCouponService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //浏览足迹数据转移
                cereBuyerFootprintService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //关联平台标签数据转移
                cereBuyerLabelService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //收货地址数据转移
                cereBuyerReceiveService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //搜索记录数据转移
                cereBuyerSearchService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //关联店铺标签数据转移
                cereBuyerShopLabelService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //提现申请数据转移
                cereBuyerWithdrawalService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //拼团单数据转移
                cereCollageOrderService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //分销员关系数据转移
                cereDistributorBuyerService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //消息数据转移
                cereNoticeService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //回答数据转移
                cereProductAnswerService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //提问数据转移
                cereProductProblemService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //购物车数据转移
                cereShopCartService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //评论数据转移
                cereShopCommentService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //订单数据转移
                cereShopOrderService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //店铺浏览数据转移
                cereShopVisitService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
            } else {
                //更新手机号已注册用户openid
                CereBuyerUser buyerUser = new CereBuyerUser();
                buyerUser.setBuyerUserId(byPhone.getBuyerUserId());
                buyerUser.setWechatOpenId(param.getWechatOpenId());
                buyerUser.setUpdateTime(time);
                //设置头像
                buyerUser.setHeadImage(param.getHeadImage());
                cereBuyerUserDAO.updateByPrimaryKeySelective(buyerUser);
                result = byPhone;
            }
        } else {
            //未绑定其他微信,更新手机号
            if (user != null) {
                user.setPhone(phone);
                user.setUpdateTime(time);
                user.setHeadImage(param.getHeadImage());
                cereBuyerUserDAO.updateByPrimaryKeySelective(user);
                result.setBuyerUserId(user.getBuyerUserId());
                result.setWechatOpenId(param.getWechatOpenId());
                result.setToken(user.getToken());
            } else {
                //新增用户
                CereBuyerUser buyerUser = new CereBuyerUser();
                buyerUser.setWechatOpenId(param.getWechatOpenId());
                buyerUser.setCreateTime(time);
                buyerUser.setPhone(phone);
                buyerUser.setToken(RandomStringUtil.getRandomCode(32, 0));
                buyerUser.setPassword(EncryptUtil.encrypt("123456"));
                buyerUser.setName("MJ" + RandomStringUtil.getRandomCode(4, 0));
                buyerUser.setState(IntegerEnum.YES.getCode());
                //设置头像
                if (!EmptyUtils.isEmpty(param.getHeadImage())) {
                    buyerUser.setHeadImage(param.getHeadImage());
                } else {
                    buyerUser.setHeadImage(StringEnum.DEFAULT_HEAD_IMAGE.getCode());
                }

                //新增分销员
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = simpleDateFormat.format(new Date());
                CereShopDistributor cereShopDistributor = new CereShopDistributor();
                cereShopDistributor.setShopId(shopId);
                cereShopDistributor.setDistributorLevelId(grade);
                cereShopDistributor.setCreateTime(format);
                cereShopDistributor.setDistributorName(buyerUser.getName());
                cereShopDistributor.setDistributorPhone(buyerUser.getPhone());
                cereShopDistributor.setState(IntegerEnum.DISTRIBUTOR_SUCCESS.getCode());
                //生成10位随机数邀请码
                cereShopDistributor.setInvitationCode(RandomStringUtil.getRandomCode(10, 0));
                //默认未清退
                cereShopDistributor.setIfLiquidation(IntegerEnum.NO.getCode());
                cereShopDistributor.setBuyerUserId(cereBuyerUser.getBuyerUserId());
                cereShopDistributorDAO.insertSelective(cereShopDistributor);


                cereBuyerUserDAO.insert(buyerUser);
                result.setBuyerUserId(buyerUser.getBuyerUserId());
                result.setWechatOpenId(param.getWechatOpenId());
                result.setToken(buyerUser.getToken());
            }
        }
        return result;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public BuyerUser updateWxPhone(UpdateWxPhoneParam param) throws CoBusinessException {
        BuyerUser result = new BuyerUser();
        result.setPhone(param.getPhone());
        String time = TimeUtils.yyMMddHHmmss();
        //校验手机号是否绑定其他微信
        CereBuyerUser cereBuyerUser = cereBuyerUserDAO.checkPhoneWx(param.getPhone());
        if (cereBuyerUser != null) {
            throw new CoBusinessException(CoReturnFormat.PHONE_ALREADY_WX);
        }
        //查询手机号已注册用户数据
        BuyerUser byPhone = cereBuyerUserDAO.findByPhone(param.getPhone());
        //查询微信已注册用户数据
        CereBuyerUser user = cereBuyerUserDAO.getByOpenid(param.getWechatOpenId());
        if (byPhone != null) {
            if (user != null) {
                //删除手机号注册用户
                cereBuyerUserDAO.deleteByPrimaryKey(byPhone.getBuyerUserId());
                //更新微信注册用户绑定手机号
                user.setPhone(byPhone.getPhone());
                user.setUpdateTime(time);
                user.setHeadImage(param.getHeadImage());
                cereBuyerUserDAO.updateByPrimaryKeySelective(user);
                result.setBuyerUserId(user.getBuyerUserId());
                result.setWechatOpenId(param.getWechatOpenId());
                result.setToken(user.getToken());
                result.setPhone(param.getPhone());
                //同步更新手机号注册的业务数据转移到微信注册用户
                //银行卡数据转移
                cereBuyerBankService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //收藏数据转移
                cereBuyerCollectService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //是否点赞数据转移
                cereBuyerCommentLikeService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //领取优惠券数据转移
                cereBuyerCouponService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                cereBuyerShopCouponService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //浏览足迹数据转移
                cereBuyerFootprintService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //关联平台标签数据转移
                cereBuyerLabelService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //收货地址数据转移
                cereBuyerReceiveService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //搜索记录数据转移
                cereBuyerSearchService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //关联店铺标签数据转移
                cereBuyerShopLabelService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //提现申请数据转移
                cereBuyerWithdrawalService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //拼团单数据转移
                cereCollageOrderService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //分销员关系数据转移
                cereDistributorBuyerService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //消息数据转移
                cereNoticeService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //回答数据转移
                cereProductAnswerService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //提问数据转移
                cereProductProblemService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //购物车数据转移
                cereShopCartService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //评论数据转移
                cereShopCommentService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //订单数据转移
                cereShopOrderService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
                //店铺浏览数据转移
                cereShopVisitService.updateBuyerData(user.getBuyerUserId(), byPhone.getBuyerUserId());
            } else {
                //更新手机号已注册用户openid
                CereBuyerUser buyerUser = new CereBuyerUser();
                buyerUser.setBuyerUserId(byPhone.getBuyerUserId());
                buyerUser.setWechatOpenId(param.getWechatOpenId());
                buyerUser.setUpdateTime(time);
                //设置头像
                buyerUser.setHeadImage(param.getHeadImage());
                cereBuyerUserDAO.updateByPrimaryKeySelective(buyerUser);
                result = byPhone;
            }
        } else {
            //未绑定其他微信,更新手机号
            if (user != null) {
                user.setPhone(param.getPhone());
                user.setUpdateTime(time);
                user.setHeadImage(param.getHeadImage());
                cereBuyerUserDAO.updateByPrimaryKeySelective(user);
                result.setBuyerUserId(user.getBuyerUserId());
                result.setWechatOpenId(param.getWechatOpenId());
                result.setToken(user.getToken());
            } else {

                //新增用户
                CereBuyerUser buyerUser = new CereBuyerUser();
                buyerUser.setWechatOpenId(param.getWechatOpenId());
                buyerUser.setCreateTime(time);
                buyerUser.setPhone(param.getPhone());
                buyerUser.setToken(RandomStringUtil.getRandomCode(32, 0));
                buyerUser.setPassword(EncryptUtil.encrypt("123456"));
                buyerUser.setName("MJ" + RandomStringUtil.getRandomCode(4, 0));
                buyerUser.setState(IntegerEnum.YES.getCode());
                //设置头像
                if (!EmptyUtils.isEmpty(param.getHeadImage())) {
                    buyerUser.setHeadImage(param.getHeadImage());
                } else {
                    buyerUser.setHeadImage(StringEnum.DEFAULT_HEAD_IMAGE.getCode());
                }
                cereBuyerUserDAO.insert(buyerUser);

                //新增分销员
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = simpleDateFormat.format(new Date());
                CereShopDistributor cereShopDistributor = new CereShopDistributor();
                cereShopDistributor.setShopId(shopId);
                cereShopDistributor.setDistributorLevelId(grade);
                cereShopDistributor.setCreateTime(format);
                cereShopDistributor.setDistributorName(buyerUser.getName());
                cereShopDistributor.setDistributorPhone(buyerUser.getPhone());
                cereShopDistributor.setState(IntegerEnum.DISTRIBUTOR_SUCCESS.getCode());
                //生成10位随机数邀请码
                cereShopDistributor.setInvitationCode(RandomStringUtil.getRandomCode(10, 0));
                //默认未清退
                cereShopDistributor.setIfLiquidation(IntegerEnum.NO.getCode());
                cereShopDistributor.setBuyerUserId(cereBuyerUser.getBuyerUserId());
                cereShopDistributorDAO.insertSelective(cereShopDistributor);

                result.setBuyerUserId(buyerUser.getBuyerUserId());
                result.setWechatOpenId(param.getWechatOpenId());
                result.setToken(buyerUser.getToken());
            }
        }
        return result;
    }

    @Override
    public BuyerUser login(LoginParam param) throws CoBusinessException {
        return cereBuyerUserDAO.findByPhone(param.getPhone());
    }

    @Override
    public void insert(CereBuyerUser buyerUser) throws CoBusinessException {
        cereBuyerUserDAO.insert(buyerUser);
        //新增分销员
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        CereShopDistributor cereShopDistributor = new CereShopDistributor();
        cereShopDistributor.setDistributorPhone(buyerUser.getPhone());
        cereShopDistributor.setShopId(shopId);
        cereShopDistributor.setDistributorLevelId(grade);
        cereShopDistributor.setCreateTime(format);
        cereShopDistributor.setDistributorName(buyerUser.getName());
        cereShopDistributor.setDistributorPhone(buyerUser.getPhone());
        cereShopDistributor.setState(IntegerEnum.DISTRIBUTOR_SUCCESS.getCode());
        //生成10位随机数邀请码
        cereShopDistributor.setInvitationCode(RandomStringUtil.getRandomCode(10, 0));
        //默认未清退
        cereShopDistributor.setIfLiquidation(IntegerEnum.NO.getCode());
        cereShopDistributor.setBuyerUserId(buyerUser.getBuyerUserId());
        cereShopDistributorDAO.insertSelective(cereShopDistributor);

    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void update(CereBuyerUser buyerUser, CereBuyerUser user) throws CoBusinessException {
        cereBuyerUserDAO.updateByPrimaryKeySelective(buyerUser);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void updatePassword(UserParam param, CereBuyerUser user) throws CoBusinessException {
        CereBuyerUser cereBuyerUser = new CereBuyerUser();
        cereBuyerUser.setBuyerUserId(user.getBuyerUserId());
        cereBuyerUser.setPassword(BCrypt.hashpw(param.getNewPassword(), BCrypt.gensalt(13)));
        cereBuyerUserDAO.updateByPrimaryKeySelective(cereBuyerUser);
    }

    @Override
    public MyUser getUser(Long buyerUserId) throws CoBusinessException {
        MyUser user = cereBuyerUserDAO.getUser(buyerUserId);
        if (user != null) {
            //查询系统未读消息数量
            int notRead = cereNoticeService.getNotRead(buyerUserId);
            //查询公告、站内信未读消息数量
            int read = cereNoticeService.getRead(buyerUserId);
            user.setNotRead(notRead + read);
        }
        return user;
    }

    @Override
    public CerePlatformCanvas getCanvas(CerePlatformCanvas canvas) {
        return cereBuyerUserDAO.getCanvas(canvas);
    }

    @Override
    public Page getSelfProblems(PageParam param, Long buyerUserId) throws CoBusinessException {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        //查询当前登录人的所有提问和对应回答数据
        List<SeckillProductProblem> list = cereProductProblemService.getSelfProblems(buyerUserId);
        if (!EmptyUtils.isEmpty(list)) {
            list.forEach(problem -> {
                //设置回答明细数据
                problem.setAnswers(cereProductAnswerService.findAnswersById(problem.getProblemId()));
            });
        }
        PageInfo<SeckillProductProblem> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    public Page getSelfAnswers(PageParam param, Long buyerUserId) throws CoBusinessException {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        //查询当前登录人的所有回答过的提问数据
        List<SeckillProductProblem> list = cereProductProblemService.getSelfAnswers(buyerUserId);
        if (!EmptyUtils.isEmpty(list)) {
            list.forEach(problem -> {
                //设置回答明细数据
                List<SeckillProductAnswer> answers = cereProductAnswerService.findAnswersById(problem.getProblemId());
                if (!EmptyUtils.isEmpty(answers)) {
                    //过滤不是当前登录人的回答数据
                    answers = answers.stream().filter(answer -> buyerUserId.equals(answer.getBuyerUserId()))
                            .collect(Collectors.toList());
                }
                problem.setAnswers(answers);
            });
        }
        PageInfo<SeckillProductProblem> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void updatePhone(UserParam param, CereBuyerUser user) throws CoBusinessException {
        BuyerUser byPhone = cereBuyerUserDAO.findByPhone(param.getPhone());
        if (byPhone != null) {
            throw new CoBusinessException(CoReturnFormat.SHOP_PHONE_ALREADY);
        }
        CereBuyerUser cereBuyerUser = new CereBuyerUser();
        cereBuyerUser.setBuyerUserId(user.getBuyerUserId());
        cereBuyerUser.setPhone(param.getPhone());
        cereBuyerUserDAO.updateByPrimaryKeySelective(cereBuyerUser);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void relievePhone(UserParam param, CereBuyerUser user) throws CoBusinessException {
        CereBuyerUser cereBuyerUser = new CereBuyerUser();
        cereBuyerUser.setBuyerUserId(user.getBuyerUserId());
        cereBuyerUserDAO.relievePhone(cereBuyerUser);
    }
}
